package io.renren.modules.job.task;

import io.renren.common.enums.CommonProcessStatus;
import io.renren.modules.customer.entity.BatchApplicationEntity;
import io.renren.modules.customer.service.BatchApplicationService;
import io.renren.thirdparty.application.BatchApplyApiClient;
import io.renren.thirdparty.application.config.PaApplicationProperties;
import io.renren.thirdparty.application.domain.ApplyRequestData;
import io.renren.thirdparty.application.domain.BatchApplyRequest;
import io.renren.thirdparty.application.domain.BatchApplyResponse;
import io.renren.thirdparty.application.domain.CustomerItem;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 批量进件定时任务
 *
 * @author sean
 * @since 2020-03-24
 */
@Component("batchSubmitApplicationTask")
public class BatchSubmitApplicationTask implements ITask {

    private static final Logger LOGGER = LoggerFactory.getLogger(BatchSubmitApplicationTask.class);

    @Autowired
    private BatchApplicationService batchApplicationService;

    @Autowired
    private PaApplicationProperties paApplicationProperties;

    @Autowired
    private BatchApplyApiClient batchApplyApiClient;

    @Override
    public void run(String params) {
        //找到处于pending状态的请求分批次进行发送
        List<BatchApplicationEntity> pendingEntities = this.batchApplicationService.getPendingRequestEntities4Apply(this.paApplicationProperties.getBatchSize());
        LOGGER.debug("Got {} pending entities for apply", pendingEntities == null ? 0 : pendingEntities.size());
        //发送
        if (pendingEntities != null && pendingEntities.size() > 0) {
            this.batchApply(pendingEntities);
        }

        //找到处于fail状态的请求分批次发送
        List<BatchApplicationEntity> failEntities = this.batchApplicationService.getFailRequestEntities4Apply(this.paApplicationProperties.getBatchSize(), this.paApplicationProperties.getMaxRetry());
        LOGGER.debug("Got {} fail entities for apply", failEntities == null ? 0 : failEntities.size());
        //发送
        if (failEntities != null && failEntities.size() > 0) {
            this.batchApply(failEntities);
        }
    }

    private void batchApply(List<BatchApplicationEntity> entities) {
        //转换为请求
        if (entities != null && entities.size() > 0) {
            Date now = new Date();

            BatchApplyRequest request = new BatchApplyRequest();
            request.setOperationType(this.paApplicationProperties.getOperationType());
            request.setPartnerId(this.paApplicationProperties.getPartnerId());
            request.setTimestamp(String.valueOf(System.currentTimeMillis()));

            //请求数据
            ApplyRequestData requestData = new ApplyRequestData();
            requestData.setChannel(this.paApplicationProperties.getChannel());
            requestData.setProductId(this.paApplicationProperties.getProductId());
            requestData.setSceneId(this.paApplicationProperties.getSceneId());
            requestData.setCustomerList(this.convertCustomerItem(entities, now));
            request.setRequestData(requestData);

            BatchApplyResponse response = this.batchApplyApiClient.submit(request);

            if (response != null && response.isSuccess()) {
                //成功则更新状态
                entities.forEach(e -> {
                    e.setRequestCount(e.getRequestCount() + 1);
                    e.setRequestTime(now);
                    e.setStatus(CommonProcessStatus.SUCCESS);
                    e.setResponse(response.toString());
                });
                this.batchApplicationService.updateBatchById(entities);
            } else {
                entities.forEach(e -> {
                    e.setRequestCount(e.getRequestCount() + 1);
                    e.setRequestTime(now);
                    e.setStatus(CommonProcessStatus.FAIL);
                    e.setResponse(response == null ? "未知错误" : response.toString());
                });
                this.batchApplicationService.updateBatchById(entities);
            }
        }
    }

    private List<CustomerItem> convertCustomerItem(List<BatchApplicationEntity> entities, Date now) {
        return entities.stream().map(e -> {
            CustomerItem item = new CustomerItem();
            item.setUserName(e.getName());
            item.setPhone(e.getMobilePhone());
            item.setCityName(e.getCity());
            item.setLoanChannel(paApplicationProperties.getLoanChannel());
            item.setChannelOrigin(StringUtils.isNotBlank(paApplicationProperties.getChannelOrigin()) ? paApplicationProperties.getChannelOrigin() : paApplicationProperties.getLoanChannel());
            item.setListFrom(StringUtils.isNotBlank(paApplicationProperties.getListFrom()) ? paApplicationProperties.getListFrom() : paApplicationProperties.getChannelOrigin());

            //item.setIpAddr("");
            if (StringUtils.isNotBlank(e.getLabel())) {
                item.setListFrom(e.getLabel());
            }

            if (e.getGender() != null) {
                item.setSex(e.getGender());
            }

            if (StringUtils.isNotBlank(e.getIdNumber())) {
                item.setIdNumber(e.getIdNumber());
            }

            item.setApplyTime(now);

            if (e.getBirthDay() != null) {
                item.setBirthday(e.getBirthDay());
                if (e.getAge() != null) {
                    item.setAge(String.valueOf(e.getAge()));
                }
            }

            if (e.getIsHouse() != null && e.getIsHouse() && e.getHousingBuyPeriod() != null) {
                item.setIsHouse(String.valueOf(1));
                item.setHousingBuyPeriod(e.getHousingBuyPeriod().getValue());
            }

            if (e.getMonthIncome() != null) {
                item.setMonthIncome(e.getMonthIncome().getValue());
            }

            if (e.getCarStatus() != null && e.getCarStatus()) {
                item.setCarStatus(String.valueOf(1));
                if (e.getCarPledgeStatus() != null && e.getCarPledgeStatus()) {
                    item.setCarPledgeStatus(String.valueOf(1));
                } else {
                    item.setCarPledgeStatus(String.valueOf(0));
                }
            }

            if (e.getPaInsuranceType() != null) {
                item.setPaInsuranceType(e.getPaInsuranceType().getValue());
            }

            if (e.getDepositPeriod() != null) {
                item.setDepositPeriod(e.getDepositPeriod().getValue());
            }

            return item;
        }).collect(Collectors.toList());
    }
}
